<script setup>
import { Message, MessageBox } from 'element-ui';
import { useRequest, useResetForm, useDownload } from '@/hooks';
import { useGlobalState } from '@/store/globalState.js';
import { getToken } from '@/utils/auth';
import { getType, getGaugesEnergy, getNoticeInfo } from '@/api/index.js';
import { TableList } from '@/components/MainComponents.js';
import InsMgTree from '@/views/zdwh/components/InsMgTree.vue';

const uploadHeaders = { Authorization: 'Bearer ' + getToken() };
const uploadUrl = useGlobalState().globalState.serverUrl + '/energyservice/gaugesEnergy/importGaugesEnergy';
const appDom = ref(null);
const upload = ref(null);
const uploadLoading = ref(false);
const contBoxHeight = ref(0);
const queryForm = ref(null);
const queryParams = ref({
  energyType: null,
  dateStart: null,
  dateEnd: null,
  enterpriseCode: '',
  dataType: null,
  areaIdName: null,
  pageNum: 1,
  pageSize: 10,
});
const dateRange = ref([]);
const fileLists = ref([]);
const extraParams = ref({
  enterPriceCode: '',
  type: 1,
});

const engTypeList = ref([]);
useRequest(getType, {
  onSuccess: res => {
    engTypeList.value = res;
  },
});
const [tableData, loading, run] = useRequest(getGaugesEnergy, {
  manual: true,
});
const [noticeInfo, , noticeRun] = useRequest(getNoticeInfo, {
  manual: true,
});
const handleQuery = () => {
  run(queryParams.value);
};
const resetQuery = () => {
  useResetForm(queryForm);
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  dateRange.value = [];
  handleQuery();
};

const checkedChange = check => {
  queryParams.value.enterpriseCode = check.enterpriseCode;
  extraParams.value.enterPriceCode = check.enterpriseCode;
  resetQuery();
  noticeRun({ enterpriseCode: check.enterpriseCode, type: 'DEVCIE_EC_API' });
};
const dateChange = val => {
  queryParams.value.dateStart = val?.[0] ?? null;
  queryParams.value.dateEnd = val?.[1] ?? null;
};
const columObj = ref({
  columnData: [
    {
      text: true,
      prop: 'statisticalTimeStr',
      width: '180px',
      label: '统计时间',
    },
    {
      text: true,
      prop: 'gaugesIdView',
      label: '计量表编号',
    },
    {
      text: true,
      prop: 'gaugesName',
      label: '计量表名称',
    },
    {
      text: true,
      prop: 'deviceTypeName',
      label: '计量表类型',
    },
    {
      text: true,
      prop: 'energyType',
      label: '能源类型',
    },
    {
      text: true,
      prop: 'energyQuantity',
      label: '能耗量',
    },
    {
      text: true,
      prop: 'unit',
      label: '能耗单位',
    },
    {
      text: true,
      prop: 'dataType',
      label: '数据来源',
    },
  ],
});
const getList = e => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  handleQuery();
};
const handleDownLoad = () => {
  useDownload('energyservice/gaugesEnergy/templateDownload', {}, '机构计量表记能耗数据模板.xlsx');
};
const handleFileSuccess = (res, file, fileList) => {
  fileLists.value = fileList;
  uploadLoading.value = false;
  if (res.msg.indexOf('覆盖') > -1) {
    MessageBox.confirm(res.msg, '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        extraParams.value.type = 0;
        fileLists.value[0].status = 'ready';
        upload.value.submit();
      })
      .catch(() => {
        fileLists.value = [];
        upload.value.clearFiles();
        resetQuery();
      });
  } else if (res.msg === '操作成功') {
    Message.success(res.msg);
    extraParams.value.type = 1;
    fileLists.value = [];
    upload.value.clearFiles();
    resetQuery();
  } else if (res.code === '500') {
    Message.error(res.msg);
    extraParams.value.type = 1;
    fileLists.value = [];
    upload.value.clearFiles();
    resetQuery();
  } else {
    Message.error(res.msg);
    extraParams.value.type = 1;
    fileLists.value = [];
    upload.value.clearFiles();
  }
};
const handleFileErroe = (err, file, fileList) => {
  uploadLoading.value = false;
  Message({
    type: 'error',
    message: err?.msg ?? '上传失败，请重新上传',
  });
  extraParams.value.type = 1;
  fileLists.value = [];
  upload.value.clearFiles();
};
const handleImport = () => {
  // uploadLoading.value = true;
};

onMounted(() => {
  nextTick(() => {
    contBoxHeight.value = appDom.value.clientHeight - queryForm.value.$el.offsetHeight - 159;
  });
});
</script>
<template>
  <div class="u-df-st u-h100" ref="appDom">
    <div class="architecture-left u-base-fg u-h100 u-br20 u-border-bg">
      <InsMgTree @checkedChange="checkedChange" :isDefaultSelect="true" />
    </div>
    <div class="architecture-right u-base-fg u-h100">
      <div class="u-df-st u-pb20 u-base-bg" v-if="noticeInfo?.msg">
        <img class="u-mr20" src="@/assets/images/notice.png" />
        <marquee direction="right" scrolldelay="100">{{ noticeInfo.msg }}</marquee>
      </div>
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="u-p20">
        <el-form-item label="能源类型" prop="energyType">
          <el-select
            class="el-input_search"
            v-model="queryParams.energyType"
            placeholder="请选择能源类型"
            size="small"
            style="width: 240px"
            clearable
          >
            <el-option v-for="item in engTypeList ?? []" :key="item.id" :label="item.energyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计时间" prop="dateStart">
          <el-form-item prop="dateEnd">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              key="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              clearable
              align="left"
              style="width: 240px"
              @change="dateChange"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="编号/名称" prop="areaIdName">
          <el-input
            v-filter-input
            v-model.trim="queryParams.areaIdName"
            placeholder="请输入设备计量表编号/名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="数据来源" prop="dataType">
          <el-select
            class="el-input_search"
            v-model="queryParams.dataType"
            placeholder="请选择数据来源"
            size="small"
            clearable
          >
            <el-option label="接口获取" value="API"></el-option>
            <el-option label="系统导入" value="IMPORT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="u-base-bg" style="height: 20px"></div>
      <div class="u-p20">
        <div class="u-df-ed u-mb20">
          <el-upload
            ref="upload"
            v-loading.fullscreen.lock="uploadLoading"
            element-loading-text="上传中..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            :limit="1"
            :show-file-list="false"
            accept=".xlsx, .xls"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :data="extraParams"
            :on-success="handleFileSuccess"
            :on-error="handleFileErroe"
            :file-list="fileLists"
            :auto-upload="true"
          >
            <el-button type="primary" plain icon="el-icon-upload2" size="small" @click="handleImport">
              数据导入
            </el-button>
          </el-upload>

          <el-button class="u-ml10" type="primary" plain icon="el-icon-download" size="small" @click="handleDownLoad">
            模板下载
          </el-button>
        </div>
        <TableList
          v-loading="loading"
          :tableData="tableData?.rows ?? []"
          :columObj="columObj"
          :height="contBoxHeight"
          :pageObj="queryParams"
          :total="tableData?.total ?? 0"
          @getList="getList"
        />
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
.u-ml10 {
  margin-left: 10px;
}
// :deep(.el-upload-dragger) {
//   width: 100% !important;
//   height: 100% !important;
//   background: transparent !important;
//   border: none !important;
// }
</style>
